﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using System.Reflection;

namespace Lib.Data

{
    public class SqlADDString<T> where T:class
    {
        /// <summary>
        /// 自动生成SQL添加语句
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static string ADD(T model)
        {
            //获取实体中的所有成员变量
            PropertyInfo[] pro = model.GetType().GetProperties();
            var aa = "";
            var cc = "(";
            var ee = "";
            //遍历出来
            foreach (var item in pro)
            {
                //逐个获取当前成员的属性
                //var a=item.PropertyType;
                int j = 0;
                var b=item.GetType();
                //判断当前变量是否是时间类型
                if (item.PropertyType.Name =="DateTime")
                {
                    j++;
                    ee=item.DeclaringType.ToString();
                    int i = ee.LastIndexOf('.') + 1;
                    ee = ee.Remove(0, i);
                    if (item.GetValue(model, null) != "0001/1/1 0:00:00")
                    {
                        aa += item.Name + ",";
                        cc += "'" + item.GetValue(model, null) + "',";
                    }
                }
                else if (item.PropertyType.Name == "String")
                {
                    aa += item.Name + ",";
                    cc += "'" + item.GetValue(model, null) + "',";
                }
                else
                {
                    if (j!=1)
                    {
                        if (item.GetValue(model, null) != null)
                        {
                            aa += item.Name + ",";
                            cc += item.GetValue(model, null) + ",";
                        }
                    }
                }
            }
            aa = aa.Remove(aa.Length - 1);
            cc = cc.Remove(cc.Length - 1);
            cc += ")";

            string dd = "insert into "+ee+"(" + aa + ") values " + cc;
            return dd;
        }   
    }
    
}
